/*
 * Project: Digital Wristwatch
 * Author: Zak Kemble, contact@zakkemble.co.uk
 * Copyright: (C) 2013 by Zak Kemble
 * License: GNU GPL v3 (see License.txt)
 * Web: http://blog.zakkemble.co.uk/diy-digital-wristwatch/
 */

#include <avr/pgmspace.h>
#include <avr/eeprom.h>
#include <stdio.h>
#include <string.h>
#include "typedefs.h"
#include "menus/diag.h"
#include "apps/battery_log.h"
#include "menu.h"
#include "menus/functions.h"
#include "devices/PCF8563.h"
#include "devices/accelerate.h"
#include "devices/battery.h"
#include "watchconfig.h"
#include "global.h"
#include "devices/oled.h"


#define OPTION_COUNT			7
#define OPTION_EXIT			0

static s_prev_menu prevMenuData;

static void mSelect(void);
static void updateTemperature(void);
static void updateVoltage(void);
static void updateFPS(void);
static void disp_sw_version(void);
static void setShowFPS(void);
static void restoreFactory(void);
static void setRestoreFactory(void);

static bool bRestoreFactory;

void mDiagOpen()
{
	setMenuInfo(OPTION_COUNT, PSTR("  < DIAGNOSTICS >"), MENU_TYPE_STR, mSelect, upOption, downOption);

	setMenuOption_P(OPTION_EXIT, menuBack, NULL, back);

	updateTemperature();
	updateVoltage();
	updateFPS();
	disp_sw_version();

	bRestoreFactory = false;
	restoreFactory();

	setPrevMenuOpen(&prevMenuData, mDiagOpen);
	
	beginAnimation2(NULL);
}

static void mSelect()
{
	setPrevMenuExit(&prevMenuData, OPTION_EXIT);
	doAction(menuData.selected == OPTION_EXIT);	
}

static void restoreFactory()
{
	const char* str;

	if(bRestoreFactory)
		str = PSTR("Confirm Restore");
	else
		str = PSTR("Restore Factory");

	setMenuOption_P(OPTION_COUNT-1, str, NULL, setRestoreFactory);
}
static void setRestoreFactory()
{
	if(!bRestoreFactory) {
		bRestoreFactory = true;
	} else {
		watchconfig_default();
		watchconfig_save();
		oled_setBrightness(watchConfig.brightness * 85);
	}
	restoreFactory();
}

static void updateTemperature()
{
	int8_t temp = accel_get_temp();

	char buff[20];
	sprintf_P(buff, PSTR("Temperature %hhdC"), temp);

	setMenuOption(1, buff, NULL, NULL);
}

static void updateVoltage()
{
	battery_update();
	uint voltage = battery_voltage();

	char buff[20];
	sprintf_P(buff, PSTR("Battery    %umV"), voltage);

	setMenuOption(2, buff, NULL, battery_log_open);
}

static void updateFPS()
{
	const char* str;
	if(watchConfig.showFPS)
		str = PSTR("Show FPS        Y");
	else
		str = PSTR("Show FPS        N");

	setMenuOption_P(3, str, NULL, setShowFPS);
}

static void disp_sw_version()
{
	char buff[26];
	sprintf_P(buff, PSTR("#Ver:%s,%s"), SW_VER, __TIME__);

	setMenuOption(4, buff, NULL, NULL);

	sprintf_P(buff, PSTR("#%s"), __DATE__);

	setMenuOption(5, buff, NULL, NULL);
}

static void setShowFPS()
{
	watchConfig.showFPS = !watchConfig.showFPS;
	updateFPS();
}
